package com.kaibes.module.file.local.listener;

import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.kaibes.module.file.local.db.FileMarkService;
import com.kaibes.module.user.UserService;
import com.kaibes.module.user.pojo.User;
import com.kaibes.orm.core.listener.DeleteListener;
import com.kaibes.orm.curd.Delete;
import com.kaibes.orm.spring.OrmListener;

@OrmListener(service = UserService.class)
public class UserDeleteListener implements DeleteListener {

    private ThreadLocal<User> threadLocal = new ThreadLocal<>();
    
    @Autowired
    private UserService userService;
    @Autowired
    private FileMarkService fileMarkService;
    
    @Override
    public void beforeDelete(Delete delete) throws SQLException {
        List<User> users = userService.list(delete.getQueries());
        if (!users.isEmpty()) {
            threadLocal.set(users.get(0));
        }
    }
    
    @Override
    public void afterClear(int count) throws SQLException {
        User user = threadLocal.get();
        threadLocal.set(null);
        fileMarkService.removeByUserId(user.getId());
    }
}
